package com.ruoyi.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.email.EmailUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.common.util.CopyEntity;
import com.common.util.ListConvertMap;
import com.common.util.MergeDataSource;
import com.param.concat.IPage;
import com.param.impl.AssignOrderParam;
import com.param.impl.GetUserDataByIdRequestParam;
import com.param.impl.IdArrayAndPage;
import com.param.impl.IdParam;
import com.param.impl.ManuscriptParams;
import com.param.impl.OrderByRejectParam;
import com.param.impl.ToExamineParamBySearch;
import com.ruoyi.center.domain.NoticeCenter;
import com.ruoyi.center.service.INoticeCenterService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.file.FileReaderContent;
import com.ruoyi.common.utils.http.FileDownloader;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.config.manager.domain.ServicePriceConf;
import com.ruoyi.config.manager.service.IServicePriceConfService;
import com.ruoyi.configuration.domain.MgNvitationRewardsConf;
import com.ruoyi.configuration.domain.MgServicePriceConf;
import com.ruoyi.configuration.service.IMgNvitationRewardsConfService;
import com.ruoyi.configuration.service.IMgServicePriceConfService;
import com.ruoyi.management.domain.CommissionManagement;
import com.ruoyi.management.domain.CommissionManagementDetail;
import com.ruoyi.management.service.ICommissionManagementDetailService;
import com.ruoyi.management.service.ICommissionManagementService;
import com.ruoyi.manager.domain.MgServiceManager;
import com.ruoyi.manager.service.IMgServiceManagerService;
import com.ruoyi.order.domain.Manuscript;
import com.ruoyi.order.domain.MgOrder;
import com.ruoyi.order.domain.MgOrderAssign;
import com.ruoyi.order.service.IManuscriptService;
import com.ruoyi.order.service.IMgOrderAssignService;
import com.ruoyi.order.service.IMgOrderService;
import com.ruoyi.order.service.IOrderLogService;
import com.ruoyi.oss.config.OssConfig;
import com.ruoyi.pay.manager.service.IPayManagerService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.team.domain.vo.MgTeam;
import com.ruoyi.team.service.ITeamInformationService;
import com.ruoyi.user.domain.MgUser;
import com.ruoyi.user.service.IMgUserService;
import com.ruoyi.web.controller.manager.tool.ZipUtil;
import com.ruoyi.web.core.config.Template;

import io.swagger.annotations.ApiOperation;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2023-12-24
 */
@RestController
@RequestMapping("/order/order")
public class MgOrderController extends BaseController {
	@Autowired
	private IMgOrderService mgOrderService;

	private ThreadPoolTaskExecutor threadPoolTaskExecutor;

	private ISysUserService userService;

	IMgUserService mgUserService;
	
	IMgOrderAssignService orderAssignService;

	INoticeCenterService centerService;

	IMgServiceManagerService serviceManager;

	IServicePriceConfService priceConfService;

	IPayManagerService priceManagerService;

	ITeamInformationService informationService;

	IMgServiceManagerService serviceManagerService;

	OssConfig ossConfig;

	ISysUserService sysUserService;

	IOrderLogService orderLogService;

	IManuscriptService manuscriptService;

	IMgNvitationRewardsConfService revitationRewardsConfService;

	ICommissionManagementService commissionManagementService;

	ICommissionManagementDetailService commissionManagementDetailService;

	IMgServicePriceConfService servicePriceConfService;

	EmailUtil emailUtil;

	Template template;

	ResourceLoader resourceLoader;

	static Map<Integer, Integer> STATUS = new HashMap<Integer, Integer>();

	static {
		// 二次服务已返搞 10 售后 11 反馈 -> 1 反馈 2 售后
		STATUS.put(1, 11);
		STATUS.put(2, 10);

	}
	
	
	@Resource
	public void setOrderAssignService(IMgOrderAssignService orderAssignService) {
		this.orderAssignService = orderAssignService;
	}

	@Resource
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	@Resource
	public void setTemplate(Template template) {
		this.template = template;
	}

	@Resource
	public void setEmailUtil(EmailUtil emailUtil) {
		this.emailUtil = emailUtil;
	}

	@Resource
	public void setServiceManagerService(IMgServiceManagerService serviceManagerService) {
		this.serviceManagerService = serviceManagerService;
	}

	@Resource
	public void setServicePriceConfService(IMgServicePriceConfService servicePriceConfService) {
		this.servicePriceConfService = servicePriceConfService;
	}

	@Resource
	public void setCommissionManagementService(ICommissionManagementService commissionManagementService) {
		this.commissionManagementService = commissionManagementService;
	}

	@Resource
	public void setCommissionManagementDetailService(
			ICommissionManagementDetailService commissionManagementDetailService) {
		this.commissionManagementDetailService = commissionManagementDetailService;
	}

	@Resource
	public void setRevitationRewardsConfService(IMgNvitationRewardsConfService revitationRewardsConfService) {
		this.revitationRewardsConfService = revitationRewardsConfService;
	}

	@Autowired
	public void setMgOrderService(IManuscriptService manuscriptService) {
		this.manuscriptService = manuscriptService;
	}

	@Autowired
	public void setOrderLogService(IOrderLogService orderLogService) {
		this.orderLogService = orderLogService;
	}

	@Resource
	public void setSysUserService(ISysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}

	@Resource
	public void setInformationService(ITeamInformationService informationService) {
		this.informationService = informationService;
	}

	@Resource
	public void setPriceManagerService(IPayManagerService priceManagerService) {
		this.priceManagerService = priceManagerService;
	}

	@Resource
	public void setServiceManager(IMgServiceManagerService serviceManager) {
		this.serviceManager = serviceManager;
	}

	@Resource
	public void setCenterService(INoticeCenterService centerService) {
		this.centerService = centerService;
	}

	@Resource
	public void setOssConfig(OssConfig ossConfig) {
		this.ossConfig = ossConfig;
	}

	@Resource
	public void setPriceConfService(IServicePriceConfService priceConfService) {
		this.priceConfService = priceConfService;
	}

	@Resource
	public void setMgUserService(IMgUserService mgUserService) {
		this.mgUserService = mgUserService;
	}

	@GetMapping("/test")
	public void test() throws IOException {

		File file = new File("./translate-template.html");

		System.out.println(file.getPath());

		emailUtil.sendMessageCarryFile("opjklu@126.com", "ddddd",
				"<html><body style='color:yeollow;'>好看好看哈哈</body></html>", file);

	}

	/**
	 * tab 栏切换
	 *
	 * @param mgOrder
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('order:list')")
	@PostMapping("listByTab")
	public TableDataInfo listByTab(@RequestBody @Validated IdArrayAndPage param) {

		PageUtils.startPage(this.getPageDomainByPost(param));

		List<MgOrder> list = mgOrderService.selectListByTab(param.getId());

		parseOrderAfter(list, null);

		return getDataTable(list);

	}

	/**
	 * 封装分页对象
	 */
	public PageDomain getPageDomainByPost(IPage page) {
		PageDomain pageDomain = new PageDomain();
		pageDomain.setPageNum(page.getPageNum());
		pageDomain.setPageSize(page.getPageSize());
		pageDomain.setReasonable(true);
		return pageDomain;
	}

	/**
	 * 查询订单列表
	 */
	@PreAuthorize("@ss.hasPermi('order:list')")
	@GetMapping("/list")
	public TableDataInfo list(MgOrder mgOrder) {
		

		String userName = mgOrder.getUserName();

		List<Long> userIds = mgOrder.getUserIds();

		Long userId = mgOrder.getUserId();

		List<MgUser> selectListByRealname = null;

		if (null != userName && 0 < userName.length()) { // 有搜索用户

			selectListByRealname = mgUserService.selectListByRealname(userName);

			if (0 == selectListByRealname.size()) {
				return getDataTable(new ArrayList<>(0));
			}
			List<Long> collect = selectListByRealname.stream().map(e -> e.getId().longValue())
					.collect(Collectors.toList());

			if (null != userId && 0 != userId.longValue()) { // 有搜索用户 id

				Object[] array = collect.stream().filter(e -> e.longValue() == userId.longValue()).toArray();

				// 看看搜出的用户中有 “ user_id 吧”
				if (0 == array.length) {
					return getDataTable(new ArrayList<>(0));
				}
			}
			userIds.addAll(collect);
		}

		// // 看看搜出的用户中有 “ user_id 吧”
		if (null != userId && 0 != userId.longValue()) {
			userIds.add(userId.longValue());
		}
		
		String processedName = mgOrder.getProcessedName();
		
		if (null != processedName) {
			// 处理编辑
			SysUser sysUser = new SysUser();
			
			sysUser.setNickName(processedName);
			List<SysUser> selectUserList = userService.selectUserList(sysUser);
			
			// 没找到
			if (0 == selectUserList.size()) {
				return getDataTable(new ArrayList<>(0));
			}
			
			List<Long> ids = selectUserList.stream().map(e -> e.getUserId()).distinct()
					.collect(Collectors.toList());
			
			mgOrder.setProcesseds(ids);
		}
		startPage();

		List<MgOrder> list = mgOrderService.selectList(mgOrder);

		parseOrderAfter(list, selectListByRealname);

		return getDataTable(list);

	}

	private void parseOrderAfter(List<MgOrder> list, List<MgUser> selectListByRealname) {
		int size = list.size();

		if (0 >= size) {
			return;
		}

		String url = "http://" + ossConfig.getURL();
		list.forEach(e -> {

			String translationProofFile = e.getTranslationProofFile();

			if (null != translationProofFile && 0 != translationProofFile.length()) {

				e.setTranslationProofFile(url + translationProofFile);
			}

			String contractFile = e.getContractFile();

			if (null != contractFile && 0 != contractFile.length()) {

				e.setContractFile(url.concat(contractFile));
			}

		});

		List<MgUser> userList;
		long[] ids;

		if (null != selectListByRealname) {
			userList = selectListByRealname;
		} else {
			ids = list.stream().mapToLong(e -> e.getUserId().longValue()).distinct().toArray();
			userList = mgUserService.getUserList(ids);
		}

		Function<MgUser, Long> function = (e) -> e.getId().longValue();

		Map<Long, MgUser> listToMapByUser = ListConvertMap.listToMap(userList, function);

		MergeDataSource<MgOrder> mergeDataSource = new MergeDataSource<MgOrder>(list);

		mergeDataSource.mergeRelease(MgOrder::getUserId, listToMapByUser, (MgOrder t, MgUser v) -> {
			MgUser user = (MgUser) v;

			t.setUserName(user.getRealname());
			return t;
		});

		ids = list.stream().filter(e -> null != e.getProcessed())
				.mapToLong(e -> e.getProcessed().longValue()).distinct().toArray();

		if (0 == ids.length || (1 == ids.length && 0 == ids[0])) {
			return;
		}

		List<SysUser> sysUsersByIds = userService.getSysUsersByIds(ids);

		Map<Long, SysUser> listToMap = ListConvertMap.listToMap(sysUsersByIds, SysUser::getUserId);

		mergeDataSource.mergeRelease(MgOrder::getProcessed, listToMap, (MgOrder t, SysUser item) -> {

			SysUser sysUser = (SysUser) item;

			t.setProcessedName(sysUser.getNickName());
			return t;
		});

	}

	/**
	 * 根据用户id查询余额支付的订单列表
	 */
	@PreAuthorize("@ss.hasPermi('recharge:use:record')")
	@GetMapping("/listRechargeByUser")
	public TableDataInfo listByUser(@Validated GetUserDataByIdRequestParam dataByIdRequestParam) {
		startPage();

		List<MgOrder> selectListByRecharge = this.mgOrderService.selectListByRecharge(dataByIdRequestParam);

		return getDataTable(selectListByRecharge);
	}

	/**
	 * 根据用户id查询订单列表
	 */
//	@PreAuthorize("@ss.hasPermi('user:order:single')")
	@GetMapping("/listByUser")
	public TableDataInfo listRechargeByUser(@Validated GetUserDataByIdRequestParam dataByIdRequestParam) {
		startPage();

		List<MgOrder> selectListByRecharge = this.mgOrderService.selectList(dataByIdRequestParam);

		long[] ids = selectListByRecharge.stream().filter(e -> null != e.getProcessed()).distinct()
				.mapToLong(e -> e.getProcessed().longValue()).toArray();

		if (0 == ids.length || (1 == ids.length && 0 == ids[0])) {
			return getDataTable(selectListByRecharge);
		}

		List<SysUser> sysUsersByIds = userService.getSysUsersByIds(ids);

		MergeDataSource<MgOrder> mergeDataSource = new MergeDataSource<MgOrder>(selectListByRecharge);

		Map<Long, SysUser> listToMap = ListConvertMap.listToMap(sysUsersByIds, SysUser::getUserId);

		mergeDataSource.mergeRelease(MgOrder::getProcessed, listToMap, (MgOrder t, SysUser item) -> {

			SysUser sysUser = (SysUser) item;

			t.setProcessedName(sysUser.getNickName());
			return t;
		});

		return getDataTable(selectListByRecharge);
	}

	/**
	 * 导出订单列表
	 */
	@PreAuthorize("@ss.hasPermi('order:order:export')")
	@Log(title = "订单", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, MgOrder mgOrder) {
		List<MgOrder> list = mgOrderService.selectList(mgOrder);
		ExcelUtil<MgOrder> util = new ExcelUtil<MgOrder>(MgOrder.class);
		util.exportExcel(response, list, "订单数据");
	}

	/**
	 * 获取订单详细信息
	 */
	@PreAuthorize("@ss.hasPermi('order:order:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Integer id) {
		MgOrder selectById = mgOrderService.selectById(id);
		
		if (null == selectById) {
			return AjaxResult.error("找不到订单");
		}
		
		MgUser user = mgUserService.selectById(selectById.getUserId().intValue());
		
		selectById.setUserName(user.getRealname());
		return success(selectById);
	}

	/**
	 * 新增订单
	 */
	@PreAuthorize("@ss.hasPermi('order:order:add')")
	@Log(title = "订单", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody MgOrder mgOrder) {
		return toAjax(mgOrderService.insert(mgOrder));
	}

	/**
	 * 修改订单
	 */
	@PreAuthorize("@ss.hasPermi('order:order:edit')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody MgOrder mgOrder) {
		return toAjax(mgOrderService.update(mgOrder));
	}

	/**
	 * 已报价
	 */
	@PreAuthorize("@ss.hasPermi('order:order:edit')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("quotation")
	@Transactional
	public AjaxResult quotation(@RequestBody MgOrder mgOrder) {

		Integer id = mgOrder.getId();

		MgOrder selectById = mgOrderService.selectById(id);

		if (null == selectById) {
			return AjaxResult.error("找不到订单");
		}

		Integer teamId = selectById.getTeamId();

		BigDecimal servicePrice = mgOrder.getServicePrice();

		mgOrder.setTotalPrice(servicePrice);

		if (null != teamId && 0 != teamId) {

			BigDecimal discount = new BigDecimal(selectById.getDiscount());

			BigDecimal divide = servicePrice.multiply(discount).divide(BigDecimal.valueOf(100));

			mgOrder.setActualPaidPrice(divide);
		} else {
			mgOrder.setActualPaidPrice(servicePrice);
		}

		// 已报价
		mgOrder.setOrderStatus(1);

		mgOrder.setTotalPrice(mgOrder.getTotalPrice());

		mgOrder.setUserStatus((byte) 1);

		int update = mgOrderService.update(mgOrder);

		int insertNoticeUser = insertNoticeUser(selectById, "平台已给出最终报价， 快去看看吧~", "已报价", (byte) 1);

		if (-1 == insertNoticeUser) {
			return AjaxResult.error("订单通知找不到服务类型：" + selectById.getServiceId());
		}

		// 1
		orderLogService.quotationLog(selectById.getId(), selectById.getUserId().intValue(), 1,
				selectById.getPayManagerId(), servicePrice);

		return toAjax(update);
	}

	private int insertNoticeUser(MgOrder mgOrder, String message, String title, byte jump) {

		List<MgServiceManager> selectMgServiceManagerList = serviceManager
				.selectMgServiceManagerList(new MgServiceManager());

		Map<Integer, MgServiceManager> listToMap = ListConvertMap.listToMap(selectMgServiceManagerList,
				MgServiceManager::getId);

		MgServiceManager mgServiceManager = listToMap.get(mgOrder.getServiceId());

		if (null == mgServiceManager) {
			return -1;
		}

		NoticeCenter center = new NoticeCenter();

		center.setUserId(mgOrder.getUserId().intValue());

		center.setNoticeType(0);

		center.setTitle(title);

		center.setTypeId(mgOrder.getId());

		center.setNoticeContent("您的【" + mgServiceManager.getTypeName() + "】订单" + mgOrder.getOrderSnId() + message);

//		center.setJump((byte) 1);

		center.setPlatform(0);

		center.setJump(jump);

		center.setAdminId(0);

		long timeMillis = System.currentTimeMillis() / 1000;

		center.setCreateTime(timeMillis);

		center.setUpdateTime(timeMillis);

		centerService.insert(center);

		return 0;
	}

	/**
	 * 更新备注
	 */
	@PreAuthorize("@ss.hasPermi('order:order:edit')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("ktRemark")
	public AjaxResult ktRemark(@RequestBody MgOrder mgOrder) {

		if (null == mgOrder.getKtRemark()) {
			return toAjax(1);
		}

		return toAjax(mgOrderService.update(mgOrder));
	}

	/**
	 * 获取编辑信息
	 *
	 * @return
	 */
	@PutMapping("getEditInfo")
	@ApiOperation(value = "编辑信息")
	public AjaxResult getEditInfo(@RequestBody @Validated IdParam param) {

		SysUser selectUserById = sysUserService.selectUserById((long) param.getId());

		return AjaxResult.success(selectUserById);

	}

	/**
	 * 更新文章标题
	 */
	@PreAuthorize("@ss.hasPermi('order:order:article')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("updateArticle")
	public AjaxResult updateArticle(@RequestBody MgOrder mgOrder) {

		String article = mgOrder.getArticle();

		if (null == article) {
			return toAjax(1);
		}

		MgOrder selectById = this.mgOrderService.selectById(mgOrder.getId());

		if (1 == selectById.getServiceType()) {
			return AjaxResult.error("作图不能修改文章");
		}

		MgOrder order = new MgOrder();

		order.setId(mgOrder.getId());

		order.setArticle(article);

		return toAjax(mgOrderService.update(mgOrder));
	}

	/**
	 * 上传拟帐合同
	 */
	@PreAuthorize("@ss.hasPermi('order:order:article')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("updateContract")
	@Transactional
	public AjaxResult updateContract(@RequestBody MgOrder mgOrder) {

		String contractFile = mgOrder.getContractFile();

		if (null == contractFile) {
			return toAjax(1);
		}

		Integer id = mgOrder.getId();

		MgOrder selectById = mgOrderService.selectById(id);

		if (null == selectById) {
			return AjaxResult.error("找不到该订单");
		}

		contractFile = contractFile.replaceAll("http://", "").replaceAll("https://", "");

		String url = ossConfig.getURL();

		contractFile = contractFile.replaceAll(url, "");

		MgOrder order = new MgOrder();

		order.setId(id);

		order.setContractFile(contractFile);

		int update = mgOrderService.update(order);

		// 通知用户端
//		您的【服务名称】订单ZF202xxxxxxxxxxX平台已上传报账合同，快去看看吧。

		NoticeCenter noticeAdmin = noticeAdmin(0, 0, selectById, "报账合同通知", "您的", "平台已上传报账合同，快去看看吧。");

		noticeAdmin.setJump((byte) 1);

		centerService.insert(noticeAdmin);

		return toAjax(update);
	}

	/**
	 * 翻译证明
	 */
	@PreAuthorize("@ss.hasPermi('order:order:article')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("updateTranslationProofContract")
	public AjaxResult updateTranslationProofContract(@RequestBody MgOrder mgOrder) {

		String article = mgOrder.getTranslationProofFile();

		if (null == article) {
			return toAjax(1);
		}

		MgOrder selectById = this.mgOrderService.selectById(mgOrder.getId());

		if (0 == selectById.getHavaTranslationProof()) {
			return AjaxResult.error("没有翻译证明上传功能");
		}

		article = article.replaceAll("http://", "").replaceAll("https://", "");

		String url = ossConfig.getURL();

		article = article.replaceAll(url, "");

		MgOrder order = new MgOrder();

		order.setId(mgOrder.getId());

		order.setTranslationProofFile(article);

		int update = mgOrderService.update(order);

		// 您的【服务名称】订单ZF202xxxxxxxxxXX平台已上传翻译润色证明，快去看看吧~

		NoticeCenter noticeAdmin = noticeAdmin(0, 0, selectById, "翻译润色证明通知", "您的", "平台已上传翻译润色证明，快去看看吧。");

		noticeAdmin.setJump((byte) 1);

		centerService.insert(noticeAdmin);

		return toAjax(update);
	}

	/**
	 * 更新字数
	 */
	@PreAuthorize("@ss.hasPermi('order:order:wordSize')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("updateWordSize")
	@Transactional
	public AjaxResult updateWordSize(@RequestBody MgOrder mgOrder) {

		Long wordSize = mgOrder.getWordSize();
		if (null == wordSize) {
			return toAjax(1);
		}

		MgOrder selectById = this.mgOrderService.selectById(mgOrder.getId());

		if (1 == selectById.getServiceType()) {
			return AjaxResult.error("作图不能修改字数");
		}

		if (0 == selectById.getWordSize().compareTo(wordSize)) {
			return AjaxResult.success();
		}

		ServicePriceConf conf = priceConfService.selectById(selectById.getServiceId());

		if (0 != conf.getBillingMethod()) {

			return AjaxResult.error("此服务已不按字数收费");
		}

		MgOrder order = this.computePrice(conf, mgOrder, selectById, wordSize.longValue());

		if (null == order) {
			return AjaxResult.success();
		}

		BigDecimal actualPaidPriceOrigial = selectById.getActualPaidPrice();

		BigDecimal price = order.getTotalPrice();

		BigDecimal currentPaidPrice = new BigDecimal(price.doubleValue());

		// 判断是否是团队订单
		Integer teamId = selectById.getTeamId();
		if (null == teamId) {
			order.setActualPaidPrice(price);
		} else {

//			MgTeam selectTeamById = informationService.selectTeamById(teamId);

//			if (null != selectTeamById) {
			BigDecimal discount = new BigDecimal(selectById.getDiscount());
			currentPaidPrice = discount.multiply(currentPaidPrice).divide(BigDecimal.valueOf(100));
			order.setActualPaidPrice(currentPaidPrice);
//			}
		}

		priceManagerService.updatePrice(selectById.getPayManagerId(),
				currentPaidPrice.subtract(actualPaidPriceOrigial));

		mgOrderService.update(order);

		return AjaxResult.success(order);
	}

	private MgOrder computePrice(ServicePriceConf conf, MgOrder param, MgOrder alreadyOrder, long wordSize) {

		BigDecimal price;

		BigDecimal urgent = BigDecimal.valueOf(0);

		// 0.25
		BigDecimal customerPrice = conf.getCustomerPrice();

		BigDecimal wordSizeBig = BigDecimal.valueOf(wordSize);

		MgOrder order = new MgOrder();

		order.setId(param.getId());

		order.setWordSize(wordSize);

		order.setServicePrice(customerPrice.multiply(wordSizeBig));

		if (1 == alreadyOrder.getUseCheckConpon()) {
			mgOrderService.update(param);
			return null;
		}

		if (1 == alreadyOrder.getUrgent()) {
			if (1 == conf.getUrgent()) { // 加急了

				BigDecimal oneHandle = BigDecimal.valueOf(100);

				BigDecimal additionalChargeRatio = conf.getAdditionalChargeRatio();

				// 0.25(1+0.5) = 0.375
//				additionalChargeRatio = oneHandle.add(additionalChargeRatio).divide(oneHandle).multiply(customerPrice);
				// 加急费
				urgent = additionalChargeRatio.divide(oneHandle).multiply(customerPrice).multiply(wordSizeBig);

				order.setUrgentMoney(urgent);

				price = wordSizeBig.multiply(customerPrice).add(urgent);

			} else {
				price = customerPrice.multiply(wordSizeBig);
			}
		} else { // // 已经不加急了
			price = customerPrice.multiply(wordSizeBig);
		}

		order.setTotalPrice(price);
		
		Integer recommendNumber = param.getRecommendNumber();
		if (null != recommendNumber) {
			order.setRecommendNumber(recommendNumber);
		}

		return order;

	}

	/**
	 * 更新字数
	 */
	@PreAuthorize("@ss.hasPermi('order:order:wordSize')")
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("updateNumberOfArticles")
	@Transactional
	public AjaxResult updateNumberOfArticles(@RequestBody MgOrder mgOrder) {

		Integer wordSize = mgOrder.getRecommendNumber();
		if (null == wordSize) {
			return toAjax(1);
		}

		MgOrder selectById = this.mgOrderService.selectById(mgOrder.getId());

		if (1 == selectById.getServiceType()) {
			return AjaxResult.error("作图不能修改字数");
		}

		if (0 == selectById.getRecommendNumber().compareTo(wordSize)) {
			return AjaxResult.success();
		}

		ServicePriceConf conf = priceConfService.selectById(selectById.getServiceId());

		if (1 != conf.getBillingMethod()) {

			return AjaxResult.error("此服务已不按篇数收费");
		}

		MgOrder order = this.computePrice(conf, mgOrder, selectById, wordSize.longValue());

		if (null == order) {
			return AjaxResult.success();
		}

		BigDecimal price = order.getTotalPrice();

		BigDecimal actualPaidPriceOrigial = selectById.getActualPaidPrice();

		BigDecimal currentPaidPrice = new BigDecimal(price.doubleValue());

		// 判断是否是团队订单
		Integer teamId = selectById.getTeamId();
		if (null == teamId) {
			order.setActualPaidPrice(price);
		} else {

			MgTeam selectTeamById = informationService.selectTeamById(teamId);

			if (null != selectTeamById) {
				BigDecimal discount = selectTeamById.getDiscount();
				currentPaidPrice = discount.multiply(currentPaidPrice).divide(BigDecimal.valueOf(100));
				order.setActualPaidPrice(currentPaidPrice);
			}
		}

		priceManagerService.updatePrice(selectById.getPayManagerId(),
				currentPaidPrice.subtract(actualPaidPriceOrigial));

		mgOrderService.update(order);

		return AjaxResult.success(order);
	}

	private void sendManuscripts(String[] files, String temp, MgOrder selectById, NoticeCenter noticeAdmin,
			String classPath, String emailTitle) {

		Map<String, Integer> map = new HashMap<String, Integer>();

		map.put("count", 0);

		String zipFile = temp.concat("/" + emailTitle + ".zip");

		try (FileOutputStream fos = new FileOutputStream(zipFile, true);
				ZipOutputStream zipOutputStream = new ZipOutputStream(fos)) {

			int len = files.length;

			for (int i = 0; i < files.length - 1; i++) {

				String currentFile = files[i];
				threadPoolTaskExecutor.execute(() -> {
					ZipUtil.zipFile(new File(currentFile), zipFile, zipOutputStream);
					Integer count = map.get("count");
					Integer integer = count;

					map.put("count", integer + 1);
				});
			}

			int fileCount = map.get("count");

			int total = 200;

			int forIndex = 0;
			for (; fileCount != len;) {

				if (fileCount >= len - 1) {
					break;
				}

				Thread.sleep(3000);
				fileCount = map.get("count");
				forIndex++;
				if (forIndex > total) {
					break;
				}
			}

			zipOutputStream.finish();
			MgUser user = mgUserService.selectById(selectById.getUserId().intValue());

			org.springframework.core.io.Resource resource = resourceLoader.getResource(classPath);

			String emailContent = FileReaderContent.read(resource.getInputStream());

			String content = noticeAdmin.getNoticeContent();

			String typeName = content.substring(content.indexOf('【') + 1, content.lastIndexOf('】'));

			emailContent = emailContent
					/* .replace("#{TITLE}", emailTitle) */.replace("#{SERVICE_NAME}", typeName)
					.replace("#{ORDER_SN}", selectById.getOrderSnId()).replace("#{TITLE}", emailTitle).trim();

			File zipFileObj = new File(zipFile);
			emailUtil.sendMessageCarryFile(user.getEmail(), emailTitle, emailContent, zipFileObj);

		} catch (Exception e1) {
			e1.printStackTrace();
		}

		files[files.length - 1] = zipFile;

		for (String string : files) {

			try {
				Files.delete(new File(string).toPath());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@Log(title = "完工确认", businessType = BusinessType.UPDATE)
	@PostMapping("completionConfirmation")
	@ApiOperation(value = "完工确认")
	@Transactional
	public AjaxResult completionConfirmation(@RequestBody @Validated IdParam param) {

		int id = param.getId();

		MgOrder selectById = mgOrderService.selectById(id);

		if (null == selectById) {
			return AjaxResult.error("订单不存在");
		}

		Integer orderStatus = selectById.getOrderStatus();
		if (6 != orderStatus) {
			return AjaxResult.error("该订单没有进入已返搞状态");
		}

		MgOrder order = new MgOrder();

		order.setId(id);

		// 判断 订单是否 已完成 ？

		Integer commentStatus = selectById.getCommentStatus();

		commentStatus = null == commentStatus ? 0 : commentStatus;

		byte userStatus = 5;

		if (1 == commentStatus) { // 已经评论
			userStatus = 8;
		}

		order.setUserStatus(userStatus);

		order.setOrderStatus(10);

		mgOrderService.update(order);

		int userIdValue = selectById.getUserId().intValue();
		orderLogService.insertLog(selectById.getId(), userIdValue, 17, selectById.getPayManagerId(), 1);

		orderLogService.insertLog(selectById.getId(), userIdValue, 5, selectById.getPayManagerId(), 0);

//		您的【服务名称】订单ZF202xxxxxXXXXXX平台已返稿，成稿已发送至您当前绑定的邮箱，请注意查收。

		// 验证是不是二次服务
		Byte serviceStatus = selectById.getServiceStatus();

		NoticeCenter noticeAdmin;

		if (0 == serviceStatus) {
			noticeAdmin = noticeAdmin(0, 0, selectById, "订单完成", "您的", "平台已返稿，成稿已发送至您当前绑定的邮箱，请注意查收。");
		} else {
			noticeAdmin = noticeAdmin(0, 0, selectById, "订单完成", "您的", "平台已返稿，成稿已发送至您当前绑定的邮箱，请注意查收。", 1);
		}

		centerService.insert(noticeAdmin);

		// 发送 成稿

		threadPoolTaskExecutor.execute(() -> {

			Manuscript manuscript = new Manuscript();

			boolean result = 0 != serviceStatus && 2 >= serviceStatus;
			if (result) {
				// 二次服务已返搞 10 售后 11 反馈 -> 1 反馈 2 售后
				manuscript.setStatus(STATUS.get(serviceStatus.intValue()));
			}
			manuscript.setOrderId(id);

			manuscript.setEditUserId(selectById.getProcessed().intValue());

			List<Manuscript> selectList = manuscriptService.selectList(manuscript);

			if (result) {
				// 获取最近一段时间的
				selectList.sort((f, s) -> s.getCreateTime().compareTo(f.getCreateTime()));

				Map<Long, List<Manuscript>> listToMap = ListConvertMap.listToMapList(selectList,
						Manuscript::getCreateTime);

				for (Long entry : listToMap.keySet()) {
					selectList = listToMap.get(entry);
					break;
				}
			}

			String url = "http://".concat(ossConfig.getURL());

			String temp = System.getenv("TEMP");

			String file;

			String[] files = new String[selectList.size() + 1];

			int index = 0;

			for (Manuscript item : selectList) {

				file = temp.concat("/").concat(item.getOriginName());

				files[index] = file;

				FileDownloader.downloadFile(url.concat(item.getFile()), file);

				index++;
			}

			// 发送邮件 及清理文件
			sendManuscripts(files, temp, selectById, noticeAdmin, template.getManuscript(),
					"来自科藤学术中心的"+noticeAdmin.getTypeName()+"成稿邮件");

		});

		// 编辑添加字数

		if (0 != serviceStatus) {
			return success();
		}

		Integer recommend = selectById.getRecommendNumber();

		Long wordSize = selectById.getWordSize();

		int realWordSize = 0;

		if (null == recommend && null != wordSize) {
			realWordSize = wordSize.intValue();
		}

		List<MgServicePriceConf> servicePriceConfByWordCount = servicePriceConfService
				.selectMgServicePriceConfByWordSize();

		// 计算当月字数

		Long processed = selectById.getProcessed();
		int computerWordSizeByThisMoth = mgOrderService.computerWordSizeByThisMoth(
				servicePriceConfByWordCount.stream().map(e -> Integer.valueOf(e.getId())).collect(Collectors.toList()),
				processed);

		sysUserService.updateParseWordSize(processed.intValue(), realWordSize, computerWordSizeByThisMoth);

		// 佣金处理

		// 金额 是否大于 1000

		if (selectById.getTotalPrice().compareTo(BigDecimal.valueOf(1000)) < 0) {
			return success();
		}

		// 计算佣金
		MgUser selectUserById = mgUserService.selectById(userIdValue);

		Long recommendNumber = selectUserById.getRecommendedUserId();

		if (recommendNumber == null || 0 == recommendNumber) {

			return success();
		}

		// 计算推荐了几个人

		CommissionManagement commissonManagent = commissionManagementService.getCommissonManagent(recommendNumber);

		if (null == commissonManagent) {
			return success();
		}

		// 判断是否推荐过
		// 被推荐人
		int userId = selectUserById.getId().intValue();

		int recommenedUserId = recommendNumber.intValue();

		CommissionManagementDetail search = new CommissionManagementDetail();

		search.setUserId(recommenedUserId);

		search.setCommissionId(commissonManagent.getId());
		
		search.setType(1);

		List<CommissionManagementDetail> commissionManagementDetails = commissionManagementDetailService
				.selectList(search);


//		if (0 < commissionManagementDetails.size()) { // 已推荐过
			// 推荐 完成
//			return success();
//		}

		// 验证 此被推荐人是否已处理过
		for (CommissionManagementDetail commissionManagementDetail : commissionManagementDetails) {

			if (userId == commissionManagementDetail.getRecommendationId().intValue()) {
				// 已获取过佣金
				return success();
			}
		}

		int countByRecommendUser = commissionManagementDetails.size() + 1;
		

		List<MgNvitationRewardsConf> listToCache = revitationRewardsConfService
				.selectMgNvitationRewardsConfList(new MgNvitationRewardsConf());

		MgNvitationRewardsConf revitationConf = null;

		for (MgNvitationRewardsConf rewardsConf : listToCache) {

			if (countByRecommendUser == rewardsConf.getInvitationNum()) {

				revitationConf = rewardsConf;

				break;
			}
		}

		if (null == revitationConf) {

			return success();
		}

		CommissionManagement updateCommissonMan = new CommissionManagement();

		Integer commissonManagentId = commissonManagent.getId();
		updateCommissonMan.setId(commissonManagentId);

		BigDecimal rewardAmount = revitationConf.getRewardAmount();
		
		updateCommissonMan.setTotalAmount(commissonManagent.getTotalAmount().add(rewardAmount));

		updateCommissonMan.setWithdrawableAmount(rewardAmount.add(commissonManagent.getWithdrawableAmount()));

		commissionManagementService.update(updateCommissonMan);

		long timeMillis = System.currentTimeMillis() / 1000L;

		CommissionManagementDetail commissionManagementDetail = new CommissionManagementDetail();

		commissionManagementDetail.setCommissionId(commissonManagentId);

		commissionManagementDetail.setUserId(recommenedUserId);

		commissionManagementDetail.setDescription("推荐用户-" + userIdValue);

		// 被推荐人
		commissionManagementDetail.setRecommendationId(userIdValue);

		commissionManagementDetail.setMonry(rewardAmount);

		commissionManagementDetail.setCreateTime(timeMillis);

		commissionManagementDetail.setType(1);

		commissionManagementDetail.setUpdateTime(timeMillis);

		commissionManagementDetailService.insert(commissionManagementDetail);

		// 通知奖励
		String content = "您邀请的用户【ID" + userId + "】已成功在平台下单，订单完成后您将获得" + rewardAmount + "元现金奖励。";
		centerService.rewardNotification(commissonManagentId, recommenedUserId, content);

		return success();
	}

	static String[][] notices = new String[][] {

			new String[] { "", "" },

			new String[] { "您的---反馈服务申请已通过，我们已加紧安排重新处理", "您的---反馈服务申请未通过，审核原因已发送至您绑定的邮箱，请注意查收。" },

			new String[] { "您的---售后服务申请已通过，我们已加紧安排重新处理", "您的---售后服务申请未通过，审核原因已发送至您绑定的邮箱，请注意查收。", },

	};

	static String[] noticeUsersContens = new String[] { "", "您有新的售后服务，---请及时查看处理!",

			"您有新的售后服务，---请及时查看处理!", };

	static String[] noticeUsersChangeServices = new String[] { "", "您的---二次服务类型已由“售后“变更为“反馈”，快去看看吧 ~",
			"您的---二次服务类型已由“反馈“变更为“售后”，快去看看吧 ~", };

	static String[] titles = new String[] { "", "反馈审核通知", "售后审核通知", };

	static String[] titlesByEmail = new String[] { "", "反馈审核", "售后审核", };
	
	@Log(title = "订单", businessType = BusinessType.UPDATE)
	@PutMapping("toExamine")
	@ApiOperation(value = "二次服务审核")
	@Transactional
	public AjaxResult toExamine(@RequestBody @Validated ToExamineParamBySearch<ManuscriptParams> mgOrder) {

		MgOrder selectById = mgOrderService.selectById(mgOrder.getId());

		if (null == selectById) {

			return AjaxResult.error("找不到此订单");
		}

		int examineService = mgOrderService.toExamineService(mgOrder);

		if (-1 == examineService) {
			return AjaxResult.error("找不到此订单");
		}

		// 您的【服务名称】订单ZF202xxxxxxxxXXX售后服务申请未通过，审核原因已发送至您绑定的邮箱，请注意查收。
		Byte status = mgOrder.getStatus();

		Byte serviceType = mgOrder.getServiceType();

		String notice = notices[serviceType][status];

		String[] split = notice.split("---");

		String title = titles[serviceType];
		NoticeCenter userCenter = this.noticeAdmin(0, 0, selectById, title, split[0], split[1], 1);

		if (1 == status) {
			// 发送邮件 拒绝 发送邮件

			threadPoolTaskExecutor.execute(() -> {

				ManuscriptParams[] manuscriptParams = mgOrder.getFiles(); // 发送稿件

				String temp = System.getenv("TEMP");

				String file;

				ManuscriptParams item;

				String[] files = new String[manuscriptParams.length + 1];

				for (int i = 0; i < manuscriptParams.length; i++) {

					item = manuscriptParams[i];

					file = temp.concat("/").concat(item.getOriginName());

					files[i] = file;

					FileDownloader.downloadFile(item.getFile(), file);
					i++;
				}

				sendManuscripts(files, temp, selectById, userCenter, template.getAfterSales(), "来自科藤学术中心的"+titlesByEmail[serviceType]+"邮件");
			});
		} else if (0 == status) {

			Long processed = mgOrder.getProcessed();
			
			if (null == processed) {
				throw new Error ("处理人不能为空");
			}
			
			// 通过 发送通知 给编辑
			String[] userTitle = noticeUsersContens[serviceType].split("---");
			
			AssignOrderParam assignOrderParam = CopyEntity.copyEntity(mgOrder, AssignOrderParam.class);
			
			
			AjaxResult commonAssign = commonAssign(assignOrderParam, selectById);

			if (!commonAssign.isSuccess()) {
				throw new Error (commonAssign.get(AjaxResult.MSG_TAG).toString());
            }
			
			NoticeCenter noticeAdmin = this.noticeAdmin(processed.intValue(), 2, selectById,
					title, userTitle[0], userTitle[1], 1);

			centerService.insert(noticeAdmin);
		}

		// 检查是否变更了售后服务
		if (serviceType != selectById.getServiceStatus()) {

			// 变更了服务
			// 向用户发送通知
//			您的【服务名称】订单ZF202xxxxxxxXxXXX二次服务类型已由“反馈“变更为“售后”，快去 当管理端【审核】时变更服务类型，用户端收到二次服务消息推送看看吧

			String[] noticeType = noticeUsersChangeServices[serviceType].split("---");

			NoticeCenter noticeAdmin = this.noticeAdmin(0, 0, selectById, "变更服务通知", noticeType[0], noticeType[1], 1);

			centerService.insert(noticeAdmin);

			orderLogService.changeServiceType(mgOrder);
		}

		orderLogService.toExamination(mgOrder);

		manuscriptService.toExamination(mgOrder);

		centerService.insert(userCenter);

		return toAjax(examineService);
	}

	// TODO 取消订单

	@Log(title = "取消订单", businessType = BusinessType.UPDATE)
	@PostMapping("cancelOrder")
	@ApiOperation(value = "取消订单")
	@Transactional
	public AjaxResult cancelOrder(@RequestBody @Validated IdParam param) {

		int id = param.getId();

		MgOrder selectById = mgOrderService.selectOrderForUpdate(id);

		if (null == selectById) {
			return AjaxResult.error("订单不存在");
		}

		// 更新状态
		MgOrder order = new MgOrder();

		order.setId(id);

		byte oneThanZero = -1;

		order.setUserStatus(oneThanZero);

		order.setOrderStatus((int) oneThanZero);

		mgOrderService.update(order);

		if(selectById.getUseCheckConpon() == 1){
			mgOrderService.cancelTicket(selectById.getUserId().intValue());
		}
		// 减去金额

		BigDecimal actualPaidPrice = selectById.getActualPaidPrice();

		if (-1 == actualPaidPrice.compareTo(BigDecimal.ZERO)) {
			throw new RuntimeException("金额不能是负数");
		}

		MgServiceManager selectMgServiceManagerById = serviceManager.selectMgServiceManagerById(selectById.getServiceId());
		
		Integer payManagerId = selectById.getPayManagerId();
		
		boolean cancelledByPayManager = this.mgOrderService.isCancelledByPayManager(payManagerId.longValue());
		
		
		priceManagerService.updatePrice(payManagerId, actualPaidPrice.negate(), cancelledByPayManager, selectMgServiceManagerById.getTypeName());

		return AjaxResult.success();

	}

	// TODO 审核二次服务 驳回编辑段，编辑待确认

	@Log(title = "驳回编辑", businessType = BusinessType.DELETE)
	@PostMapping("reject")
	@ApiOperation(value = "驳回编辑")
	@Transactional
	public AjaxResult reject(@RequestBody @Validated OrderByRejectParam param) {

		int id = param.getId();

		MgOrder selectById = mgOrderService.selectById(id);

		if (null == selectById) {
			return AjaxResult.error("订单不存在");
		}
		
		if (0 == selectById.getOrderStatus().compareTo(7)) {
			return AjaxResult.error("订单已驳回");
		}

		// 更新状态
		MgOrder order = new MgOrder();

		order.setId(id);

		order.setEditStatus((byte) 3);

		order.setOrderStatus(7);

		String reason = param.getReason();
		order.setReason(reason);
		
		MgOrderAssign selectByOrderIdAndProcessd = orderAssignService.selectByOrderIdAndProcessd(id, selectById.getProcessed().intValue());
		
		MgOrderAssign orderAssign = new MgOrderAssign();
		
		orderAssign.setId(selectByOrderIdAndProcessd.getId());
		
		orderAssign.setEditStatus((byte) 3);
		
		orderAssign.setOrderStatus(7);
		
		orderAssignService.update(orderAssign);
		
		mgOrderService.update(order);
       
		
		// 添加订单日志
		orderLogService.insertLog(selectById.getId(), selectById.getUserId().intValue(), 18,
				selectById.getPayManagerId(), 1, reason);

		// 您提交的【服务名称】订单ZF202xxxxXXXXXXX已被平台驳回，驳回原因:这里是管理端填写的驳回内容
		NoticeCenter noticeAdmin = noticeAdmin(selectById.getProcessed().intValue(), 2, selectById, "稿件重审通知", "您提交的",
				"已被平台驳回，驳回原因:" + reason);

		centerService.insert(noticeAdmin);

		return success();
	}

	/**
	 * 指派订单
	 */
	@PreAuthorize("@ss.hasPermi('order:order:assignOrder')")
	@Log(title = "订单", businessType = BusinessType.DELETE)
	@PutMapping("assignOrder")
	@Transactional
	public AjaxResult assignOrder(@RequestBody @Validated AssignOrderParam param) {

		Integer id = param.getId();
		MgOrder selectById = mgOrderService.selectById(id);
		AjaxResult commonAssign = commonAssign(param, selectById);
		
		noticeCenter(param, selectById);
		
		return commonAssign;
	}

	protected AjaxResult commonAssign(AssignOrderParam param, MgOrder selectById) {
		Integer id = param.getId();

		if (null == selectById) {
			return AjaxResult.error("订单不存在");
		}

		Long processed = selectById.getProcessed();
//		if (null != processed && 0 != processed) {
//			return AjaxResult.error("订单已派搞");
//		}

		Byte serviceStatus = selectById.getServiceStatus();
		
		if (0 == serviceStatus &&  0 != processed && processed.longValue() != param.getProcessed().longValue()) {
			return AjaxResult.error("派搞后不支持更换其他编辑");
		}
		
//
//		if (null != selectByOrderIdAndProcessd) {
//			return AjaxResult.error("已指派过该处理人");
//		}
		
		MgOrder order = CopyEntity.copyEntity(param, MgOrder.class);

//		order.setParseTime(System.currentTimeMillis() /1000);

		order.setOrderStatus(4);

		long timeMillis = System.currentTimeMillis();
		order.setDispatchTime(timeMillis / 1000);

		order.setEditStatus((byte) 0);

		order.setUserStatus((byte) 4);
		
		order.setParseTime(0L);

		
		int update = mgOrderService.update(order);

		int insertNoticeUser = insertNoticeUser(selectById, "已进入处理中，请随时关注订单状态", "处理订单", (byte) 1);

		
		if (-1 == insertNoticeUser) {
			return AjaxResult.error("订单通知找不到服务类型：" + selectById.getServiceId());
		}
		
		param.setUserId(selectById.getUserId());
		
		param.setOrderStatus(order.getOrderStatus());
		
		param.setEditStatus(order.getEditStatus());
		
		param.setOrderSn(selectById.getOrderSnId());
		param.setOrderId(id.longValue());
		
		param.setPayManagerId(selectById.getPayManagerId());
		
		param.setServiceName(selectById.getServiceTypeName());
		
		param.setServiceId(selectById.getServiceId());
		
		param.setRemarks(selectById.getRemarks());
		
		param.setServiceStatus(serviceStatus);
		
		param.setWordSize(selectById.getWordSize());
		
		param.setTargetJournal(selectById.getTargetJournal());
		
		param.setId(null);

//		MgOrderAssign selectByOrderIdAndProcessd = orderAssignService.selectByOrderIdAndProcessd(id, processed.intValue());

//		if (null == selectByOrderIdAndProcessd) {
			
		// 记录处理人列表
		orderAssignService.selectProcessPersonal(param);
			
//		} else {
//			
//			param.setUpdateTime(System.currentTimeMillis() / 1000);
//			
//			param.setDispatchTime(System.currentTimeMillis() / 1000);
//			
//			param.setId(selectByOrderIdAndProcessd.getId().intValue());
//			
//			orderAssignService.updateParam(param);
//		}
		
		
		
		
		orderLogService.insertLog(selectById.getId(), selectById.getUserId().intValue(), 19,
				selectById.getPayManagerId(), 1);

		// 用户端状态 待处理
		orderLogService.insertLog(selectById.getId(), selectById.getUserId().intValue(), 4,
				selectById.getPayManagerId(), 0);

		

		return toAjax(update);
	}

	protected void noticeCenter(AssignOrderParam param, MgOrder selectById) {
		NoticeCenter noticeCenter = noticeAdmin(param.getProcessed().intValue(), 
				2, selectById, "派稿通知", "您有新的平台派稿",
				"请及时查看处理!");

		centerService.insert(noticeCenter);
	}

	protected NoticeCenter noticeAdmin(int processed, int platform, MgOrder selectById, String title, String prefix,
			String suffix) {
		return noticeAdmin(processed, platform, selectById, title, prefix, suffix, 0);
	}

	protected NoticeCenter noticeAdmin(int processed, int platform, MgOrder selectById, String title, String prefix,
			String suffix, int type) {
		// 给编辑发送通知

		List<MgServiceManager> selectMgServiceManagerList = serviceManager
				.selectMgServiceManagerList(new MgServiceManager());

		Map<Integer, MgServiceManager> listToMap = ListConvertMap.listToMap(selectMgServiceManagerList,
				MgServiceManager::getId);

		NoticeCenter noticeCenter = new NoticeCenter();

		noticeCenter.setTitle(title);

		MgServiceManager mgServiceManager = listToMap.get(selectById.getServiceId());

		String typeName = mgServiceManager.getTypeName();

		noticeCenter.setTypeName(typeName);

		noticeCenter.setNoticeContent(prefix + "【" + typeName + "】订单" + selectById.getOrderSnId() + "，" + suffix);

		noticeCenter.setTypeId(selectById.getId());

		noticeCenter.setUserId(selectById.getUserId().intValue());

		noticeCenter.setNoticeType(type);

		noticeCenter.setPlatform(platform);

		noticeCenter.setAdminId(processed);
		return noticeCenter;
	}

	/**
	 * 指派订单无日志
	 */
	@PreAuthorize("@ss.hasPermi('order:order:assignOrder')")
	@Log(title = "订单", businessType = BusinessType.DELETE)
	@PutMapping("assignOrderNoLog")
	@ApiOperation(value = "指派订单无日志")
	@Transactional
	public AjaxResult assignOrderNoLog(@RequestBody @Validated AssignOrderParam param) {

		Integer id = param.getId();

		MgOrderAssign assignOrderById = orderAssignService.selectById(id);

		if (null == assignOrderById) {
			return AjaxResult.error("编辑订单不存在");
		}

		int orderId = assignOrderById.getOrderId().intValue();
		MgOrder selectById = mgOrderService.selectById(orderId);
		//
		if (null == selectById) {
			return AjaxResult.error("订单不存在");
		}
		Long processed = selectById.getProcessed();
//
		if (null == processed) {

			processed = 0L;
		}
//
		Long tmp = assignOrderById.getProcessed();

		if (0 == tmp.compareTo(processed)) { // 处理人一致
			// 修改 主表派单 消息
			MgOrder order = CopyEntity.copyEntity(param, MgOrder.class);

			order.setId(orderId);
			
			mgOrderService.update(order);
		}
		
		
		MgOrderAssign assign = new MgOrderAssign();
		
		assign.setOrderId((long) orderId);
		
		assign.setId(id.longValue());
		
		assign.setOrderSn(selectById.getOrderSnId());
		
		assign.setProcessed(param.getProcessed());
		
		assign.setUserId(selectById.getUserId());
		
		assign.setProcessMoney(param.getProcessMoney());
		
		orderAssignService.update(assign);
		
		return toAjax(1);
	}
	
	
//	@PreAuthorize("@ss.hasPermi('order:order:assignOrder')")
//	@Log(title = "订单", businessType = BusinessType.DELETE)
//	@PutMapping("assignOrderNoLog")
//	@ApiOperation(value = "指派订单无日志")
//	@Transactional
//	public AjaxResult assignOrderNoLog(@RequestBody @Validated AssignOrderParam param) {
//
//		Integer id = param.getId();
//
//		MgOrder selectById = mgOrderService.selectById(id);
//
//		if (null == selectById) {
//			return AjaxResult.error("订单不存在");
//		}
//
//		Long processed = selectById.getProcessed();
//
//		if (null == processed) {
//
//			processed = 0L;
//		}
//
//		long tmp = processed;
//
//		if (0 != tmp && tmp != param.getProcessed().longValue()) {
//			return AjaxResult.error("派搞后不支持更换其他编辑");
//		}
//
//		MgOrder order = CopyEntity.copyEntity(param, MgOrder.class);
//
//		mgOrderService.update(order);
//
//		Integer assignId = orderAssignService.getOrderAssignsMaxIdForUpdate(id, param.getProcessed());
//		
//		
//		MgOrderAssign assign = new MgOrderAssign();
//		
//		assign.setOrderId(id.longValue());
//		
//		assign.setId(assignId.longValue());
//		
//		assign.setOrderSn(selectById.getOrderSnId());
//		
//		assign.setProcessed(param.getProcessed());
//		
//		assign.setUserId(selectById.getUserId());
//		
//		assign.setProcessMoney(param.getProcessMoney());
//		
//		orderAssignService.update(assign);
//		
//		return toAjax(1);
//	}

	/**
	 * 删除订单
	 */
	@PreAuthorize("@ss.hasPermi('order:order:remove')")
	@Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Integer[] ids) {
		return toAjax(mgOrderService.deleteByIds(ids));
	}

	@Autowired
	public void setUserService(ISysUserService userService) {
		this.userService = userService;
	}

	@Autowired
	public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor threadPoolTaskExecutor) {
		this.threadPoolTaskExecutor = threadPoolTaskExecutor;
	}
}
